from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import json


def index(request):
    return render(request,'index.html')


def getcookie(request):
    # 根据cookie获取name
    response = HttpResponse()
    name = str(request.COOKIES.get('name'))
    if name == 'None':
        response.content = json.dumps({"statu": "F", "code": "403", "msg": "Auth is None"})
    else:
        response.content = json.dumps({"statu":"S","code":"000","msg":"欢迎，{}".format(name)})
    response.flush()
    return response


@csrf_exempt
def login(request):
    # 解析json请求体
    reps = json.loads(str(request.body,encoding='utf-8'))
    user = reps['user']
    password = reps['password']
    response = HttpResponse()
    # 用户名正确
    if user == 'felix':
        # 密码正确
        if password == '123456':
            response.set_cookie('name',user)
            response.content =json.dumps({"statu":"S","code":"000","msg":"登录成功"})
            return response
        # 密码错误
        else:
            response.content =json.dumps({"statu": "F", "code": "011", "msg": "密码错误"})
            return response
    # 用户名不存在
    else:
        response.content = json.dumps({"statu": "F", "code": "012", "msg": "用户不存在"})
        return response

